<template>
  <div>
    <div class="header-top">
      <div class="header-wrap">
        <div>
          尚品汇欢迎您！请 <router-link to="/login">登录</router-link> |
          <router-link to="/registry">免费注册</router-link>
        </div>
        <div class="header-nav">
          <span>我的订单</span>
          <span>我的购物车</span>
          <span>我的尚品汇</span>
          <span>尚品汇会员</span>
          <span>企业采购</span>
          <span>关注尚品汇</span>
          <span>合作招商</span>
          <span class="header-nav-last">商家后台</span>
        </div>
      </div>
    </div>
    <div class="header-bottom">
      <img @click="goHome" src="./imgs/logo.png" alt="logo" />
      <!-- 阻止默认行为 既可以在按钮处绑定事件，也可以在表单处绑定事件 -->
      <form @submit.prevent="goSearch">
        <input v-model="keyword" class="header-ipt" type="text" />
        <button class="header-btn">搜索</button>
      </form>
    </div>
    <div></div>
  </div>
</template>

<script>
export default {
  name: "MyHeader",
  data() {
    return {
      keyword: this.$route.query.keyword,
    };
  },
  methods: {
    goSearch() {
      // 获取用户输入的关键字
      const keyword = this.keyword;
      const query = this.$route.query;
      // 声明一个常量
      const option = {
        name: "Search",
        // 🐷因为会被认为是同一个query所以会不跳转，需要换壳
        query: {
          ...query,
        },
      };
      // 判断
      if (keyword) {
        option.query.keyword = keyword;
      } else {
        delete option.query.keyword;
      }
      // 编程式导航
      this.$router.history.push(option);
    },
    goHome() {
      this.$router.push("/home");
    },
  },
  watch: {
    $route($route) {
      this.keyword = $route.query.keyword;
    },
  },
};
</script>

<style lang="less" scoped>
.header-top {
  background-color: #eaeaea;
}
.header-wrap {
  height: 30px;
  width: 1200px;
  margin: 0 auto;
  line-height: 30px;
  display: flex;
  justify-content: space-between;
}
.header-nav span {
  padding: 0 10px;
  border-right: 1px solid #b3aeae;
}
.header-nav .header-nav-last {
  border-right: none;
  padding-right: 0;
}
.header-bottom {
  width: 1200px;
  height: 100px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-ipt {
  width: 500px;
  box-sizing: border-box;
  padding: 5.4px 5px 5px 5px;
  border: 2px solid #ea4a36;
  border-right: none;
  outline: none;
}
.header-btn {
  width: 80px;
  height: 30px;
  border: none;
  outline: none;
  background-color: #ea4a36;
  color: #fff;
  cursor: pointer;
}
</style>
